package com.nav.games.app.usermgmt;

import java.util.Locale;

import javax.servlet.http.HttpServletResponse;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.hibernate.HibernateException;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.Transaction;
import org.hibernate.exception.ConstraintViolationException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.MessageSource;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;

import com.nav.games.app.busobj.def.User;

@Controller
@RequestMapping("/signup")
public class SignupAction {
	protected final Log logger = LogFactory.getLog(getClass());
	
	@Autowired
	private SessionFactory sessionFactory;
	
	@Autowired
	private MessageSource messageSource;
	
	public void setSessionFactory(SessionFactory sessionFactory) {
        this.sessionFactory = sessionFactory;
    }
	
	public void setMessageSource(MessageSource messageSource) {
		this.messageSource = messageSource;
	}

	@RequestMapping(method = RequestMethod.POST)
	public String execute(@ModelAttribute(value="user")User user, Locale locale, ModelMap map, HttpServletResponse response) throws Exception {
		Session session = sessionFactory.openSession();
		Transaction tx = null;
		try {
			tx = session.beginTransaction();
			session.save(user);
			tx.commit();
			map.addAttribute("message", messageSource.getMessage("successmsg.signup", null, locale));
			return "success-message";
		} catch(ConstraintViolationException e) {
			response.setStatus(600);
			map.addAttribute("message", messageSource.getMessage("errormsg.alreadyregistered", null, locale));
			return "failure-message";
		} catch(HibernateException e) {
			if (tx != null)
				tx.rollback();
		} finally {
			session.close();
		}
		response.setStatus(600);
		map.addAttribute("message", messageSource.getMessage("errormsg.unknown", null, locale));
		return "failure-message";
	}
}
